import 'package:flutter/material.dart';
import 'package:ichinesereader/constants.dart';
import 'package:ichinesereader/controller/cache.dart';
import 'package:ichinesereader/controller/evaluation.dart';
import 'package:ichinesereader/models/evaluation/evaluationSkillProgressResult.dart';
import 'package:ichinesereader/models/evaluation/evaluationSkillType.dart';
import 'package:ichinesereader/themes/appTheme.dart';
import 'package:ichinesereader/utils/helper.dart';
import 'package:ichinesereader/utils/log.dart';
import 'package:ichinesereader/widgets/layouts/customAppBar.dart';
import 'package:hive_flutter/hive_flutter.dart';
import 'package:get/get.dart';
import 'package:percent_indicator/linear_percent_indicator.dart';
import 'package:syncfusion_flutter_datagrid/datagrid.dart';

class EvaluationLinguisticSkillProgressDataGrid extends StatefulWidget {
  EvaluationLinguisticSkillProgressDataGrid({Key? key, required this.skillType})
      : super(key: key);
  final String skillType;

  @override
  State<EvaluationLinguisticSkillProgressDataGrid> createState() =>
      _EvaluationLinguisticSkillProgressDataGridState();
}

class _EvaluationLinguisticSkillProgressDataGridState
    extends State<EvaluationLinguisticSkillProgressDataGrid> {
  final box = Hive.box('appconfig');
  final EvaluationController controller = Get.find();

  bool isWebOrDesktop = GetPlatform.isMacOS || GetPlatform.isWeb;
  bool isSchoolAdmin = true;
  List<DataGridRow> dataGridRows = <DataGridRow>[];
  DataGridController _dataGridController = DataGridController();
  List<SkillProgressItem> skillProgressItems = [];
  EvaluationSkillType evaluationSkillType = EvaluationSkillType();
  int _currentLevel = 1;

  @override
  void initState() {
    String _classId = box.get(CacheManagerKey['currentclass'].toString()) ?? '';
    bool isTeacher = box.get(CacheManagerKey['nanhairole'].toString()) ==
        Constants.NanhaiRole_Teacher;
    evaluationSkillType = Constants.evaluationLinguisticTypes
        .where((element) => element.skill == widget.skillType)
        .first;

    try {
      if (isTeacher) {
        _currentLevel = (box.get(CacheManagerKey['eveluationlevel'].toString(),
                                defaultValue: 1) as double)
                            .toInt();
      } else {
        _currentLevel = int.tryParse(
                box.get("UserLevel").toString().replaceAll('level', '')) ??
            1;
      }
    } catch (error) {
      _currentLevel = 1;
    }

    Future.delayed(Duration(milliseconds: 200), () {
      if (_classId != '') {
        controller.fetchEvaluationLinguisticKnowledgesProgressData(
            _classId, _currentLevel.toString(), evaluationSkillType.value);
      }
    });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    Log.debug('build evaluation proficiency skill progress datagrid');

    return Scaffold(
      //backgroundColor: Colors.transparent,
      appBar: CustomAppBar(title: evaluationSkillType.skill.toString()),
      body: Center(
        child: Column(
          children: [
            Expanded(
              child: controller.obx(
                (data) {
                  if (controller.evaluationSkillProgressData.length > 0) {
                    skillProgressItems = controller.evaluationSkillProgressData;
                    return _buildDataGrid();
                  } else {
                    return Visibility(
                      child: Text(''),
                      visible: false,
                    );
                  }
                },
                // onLoading: Center(
                //     child: CircularProgressIndicator(
                //   backgroundColor: Get.theme.primaryColorDark,
                //   strokeWidth: 9.0,
                // )),
              ),
            ),
          ],
        ),
      ),
    );
  }

  Stack _buildDataGrid() {
    if (GetPlatform.isDesktop || GetPlatform.isWeb) isWebOrDesktop = true;
    return Stack(
      alignment: Alignment.topLeft,
      children: [
        Container(
          //width: 1350,
          padding: EdgeInsets.only(
            right: 15,
          ),
          margin: EdgeInsets.all(27),
          decoration: BoxDecoration(
            gradient: Get.isDarkMode
                ? LinearGradient(
                    colors: [
                      Color(0xff111111),
                      Colors.black,
                    ],
                    begin: Alignment.topLeft,
                    end: Alignment(2.0, 1.0),
                  )
                : LinearGradient(
                    colors: [
                      Get.theme.primaryColorLight,
                      Get.theme.primaryColorLight,
                      Get.theme.primaryColor,
                    ],
                    begin: Alignment.topLeft,
                    end: Alignment(2.0, 1.0),
                  ),
            borderRadius: BorderRadius.only(
              topLeft: Radius.circular(12.0),
              topRight: Radius.circular(12.0),
              bottomLeft: Radius.circular(12.0),
              bottomRight: Radius.circular(72.0),
            ),
            boxShadow: [
              BoxShadow(
                blurRadius: 12,
                spreadRadius: 1,
                color: Get.isDarkMode
                    ? Get.theme.primaryColor
                    : Colors.black.withOpacity(0.1),
                offset: Offset(9, 9),
              ),
            ],
          ),
        ),
        Container(
          //width: 1200,
          padding: EdgeInsets.all(42),
          decoration: BoxDecoration(
            color: Get.isDarkMode ? Colors.black : Colors.white,
            borderRadius: BorderRadius.only(
              topLeft: Radius.circular(12.0),
              topRight: Radius.circular(12.0),
              bottomLeft: Radius.circular(12.0),
              bottomRight: Radius.circular(72.0),
            ),
            boxShadow: [
              BoxShadow(
                blurRadius: 12,
                spreadRadius: 1,
                color: Get.isDarkMode
                    ? Get.theme.primaryColor
                    : Colors.black.withOpacity(0.1),
                offset: Offset(9, 9),
              ),
            ],
          ),
          child: SfDataGrid(
            source: SkillProgressDataGridSource(items: skillProgressItems),
            onQueryRowHeight: (row) {
              return row.rowIndex == 0 ? 50.0 : 49.0;
            },
            //设置表头高度
            showCheckboxColumn: false,
            rowsPerPage: 15,
            allowSorting: true,
            allowTriStateSorting: true,
            selectionMode: SelectionMode.single,
            navigationMode: GridNavigationMode.row,
            controller: _dataGridController,
            columns: <GridColumn>[
              GridColumn(
                columnName: 'FirstName',
                width: isWebOrDesktop ? 180 : 180,
                label: buildDataGridColumnLabel('FirstName'),
              ),
              GridColumn(
                width: 180,
                columnName: 'LastName',
                label: buildDataGridColumnLabel('LastName'),
              ),
              GridColumn(
                columnName: 'Progress',
                width: 480,
                label: buildDataGridColumnLabel('Progress'),
              ),
              GridColumn(
                columnName: 'UserName',
                width: 10,
                visible: false,
                label: buildDataGridColumnLabel('UserName'),
              ),
            ],
          ),
        ),
      ],
    );
  }
}

class SkillProgressDataGridSource extends DataGridSource {
  SkillProgressDataGridSource({required List<SkillProgressItem> items}) {
    dataGridRows = items
        .map<DataGridRow>((dataGridRow) => DataGridRow(cells: [
              DataGridCell<String>(
                  columnName: 'FirstName', value: dataGridRow.firstName),
              DataGridCell<String>(
                  columnName: 'LastName', value: dataGridRow.lastName),
              DataGridCell<double>(
                  columnName: 'Progress',
                  value:
                      dataGridRow.progress! * 100 / dataGridRow.total!.toInt()),
              DataGridCell<String>(
                  columnName: 'UserName', value: dataGridRow.userName),
            ]))
        .toList();
  }

  List<DataGridRow> dataGridRows = [];

  @override
  List<DataGridRow> get rows => dataGridRows;

  @override
  DataGridRowAdapter? buildRow(DataGridRow row) {
    //列表隔行Row的颜色 // https://help.syncfusion.com/flutter/datagrid/conditional-styling
    Color setRowBackgroundColor() {
      final int index = effectiveRows.indexOf(row);
      if (index % 2 != 0) {
        return Get.isDarkMode ? Colors.black : Colors.grey[200]!;
      }
      return Colors.transparent;
    }

    return DataGridRowAdapter(
        color: setRowBackgroundColor(),
        cells: row.getCells().map<Widget>((dataGridCell) {
          if (dataGridCell.columnName == 'Progress') {
            double process = dataGridCell.value ?? 0;
            return Container(
              padding: EdgeInsets.symmetric(horizontal: 8.0),
              child: LinearPercentIndicator(
                animation: true,
                lineHeight: 18.0,
                animationDuration: 1000,
                percent: process.toDouble() / 100,
                center: Text(
                  "${process.toStringAsFixed(2)}%",
                  style: TextStyle(color: Colors.black),
                ),
                progressColor: Get.theme.primaryColor,
                barRadius: Radius.circular(16),
                backgroundColor: AppTheme.colors.disableBtnLight,
              ),
            );
          } else {
            return Container(
                alignment: Alignment.centerLeft,
                padding: EdgeInsets.symmetric(horizontal: 15.0),
                child: Text(
                  dataGridCell.value.toString(),
                  overflow: TextOverflow.ellipsis,
                  style: Get.textTheme.bodySmall,
                ));
          }
        }).toList());
  }
}
